package com.usian.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.model.article.ApAuthor;
import com.usian.model.behavior.dtos.FollowBehaviorDto;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserFan;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.user.feign.ArticleFeign;
import com.usian.user.mapper.ApUserFanMapper;
import com.usian.user.mapper.ApUserFollowMapper;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserRelationService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    private ApUserFollowMapper apUserFollowMapper;
    @Autowired
    private ApUserFanMapper apUserFanMapper;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;


    @Override
    public ResponseResult follow(UserRelationDto dto) {

        //1.参数检查
        if(dto.getOperation() == null || dto.getOperation()<0 || dto.getOperation() > 1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getAuthorId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"作者信息不能为空");
        }

        //获取作者的详情  远程调用
        ApAuthor apAuthor = articleFeign.findById(dto.getAuthorId());
        if(apAuthor ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }else{
            //获取关注作者详情
            Integer followId = apAuthor.getUserId();
            //获取本人信息
            ApUser apUser = AppThreadLocalUtils.getUser();
            Integer userId = (Integer) apUser.getId();

            if(userId>0){
                //0：关注，1：取消关注
                if(dto.getOperation()==0){
                    return followByUserId(apUser,followId,dto.getArticleId());
                }else if(dto.getOperation()==1){
                    return followCancelByUserId(apUser,followId);
                }
            }

        }
        return null;
    }

    //取消关注
    public ResponseResult followCancelByUserId(ApUser apUser,Integer followId){
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, apUser.getId())
                .eq(ApUserFollow::getFollowId, followId));
        if(apUserFollow==null){
            //以前没有关注过，现在取消关注 没什么意义
            return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"未关注");
        }else{
            //关注过，但是现在要取消关注
            //删除follow
            apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                    .eq(ApUserFollow::getUserId, apUser.getId()).eq(ApUserFollow::getFollowId, followId));
            //删除fan
            ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                    .eq(ApUserFan::getUserId, followId).eq(ApUserFan::getFansId, apUser.getId()));
            //删除用户粉丝信息
            if(apUser != null){
                apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, followId).eq(ApUserFan::getFansId, apUser.getId()));
            }
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }

    //关注用户  follow   fan   插入数据
    private ResponseResult followByUserId(ApUser apUser,Integer followId,Long articleId){
        //从用户表中根据用户id 获取用户昵称
        ApUser followUser = apUserMapper.selectById(followId);
        if(followUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关注用户不存在");
        }

        //关注   follow    fan
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, apUser.getId())
                .eq(ApUserFollow::getFollowId, followId));
        if(apUserFollow ==null){

            ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, followId).eq(ApUserFan::getFansId, apUser.getId()));
            //保存app用户粉丝信息
            if(apUserFan == null){
                apUserFan = new ApUserFan();
                apUserFan.setUserId(followId);
                apUserFan.setFansId(apUser.getId().longValue());
                apUserFan.setFansName(followUser.getName());
                apUserFan.setLevel((short)0);
                apUserFan.setIsDisplay(true);
                apUserFan.setIsShieldLetter(false);
                apUserFan.setIsShieldComment(false);
                apUserFan.setCreatedTime(new Date());
                apUserFanMapper.insert(apUserFan);
            }

            //保存app用户关注信息
            apUserFollow = new ApUserFollow();
            apUserFollow.setUserId(apUser.getId());
            apUserFollow.setFollowId(followId);
            apUserFollow.setCreatedTime(new Date());
            apUserFollow.setIsNotice(true);
            apUserFollow.setLevel((short)1);
            apUserFollowMapper.insert(apUserFollow);


            //发送kafka消息 记录用户关注行为
            FollowBehaviorDto followBehaviorDto =new FollowBehaviorDto();
            followBehaviorDto.setArticleId(articleId);
            followBehaviorDto.setFollowId(followId);
            followBehaviorDto.setUserId(apUser.getId());
            kafkaTemplate.send("follow.behavior.topic", JSON.toJSONString(followBehaviorDto));




            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"已关注");
        }
    }
}


